import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'package:hello_flutter/page/ProfilePage.dart';
import 'package:hello_flutter/util/PATClient.dart';
import 'package:hello_flutter/util/TFSClient.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:hello_flutter/domain/AppData.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  AppData appdata;

  Future<String> _onLogin(LoginData loginData) async {
    print("_onLogin pat ${loginData.password}");
    try {
      var resp = await PATClient(loginData.password)
          .get('${appdata.collectionUrl}/_api/_common/GetUserProfile')
          .timeout(Duration(seconds: 5));
      if (resp.statusCode != 200) throw 'status ${resp.statusCode}';
      //保存pat
      appdata.userPAT = loginData.password;
      await appdata.refresh();
    } catch (e) {
      print('发生异常 $e');
      return e.toString();
    }
    return null;
  }

  Future<String> _onSignUp(String s) async {
    print("onSignup $s");
    if (s == 'back') {
      //返回
    } else {
      //go web
      Navigator.pushNamed(context, "/web");
    }
    return '';
  }

  SharedPreferences prefs;

  LoginPage() {
    SharedPreferences.getInstance().then((value) => this.prefs = value);
  }

  @override
  Widget build(BuildContext context) {
    this.appdata = Provider.of<AppData>(context, listen: false);
    return FlutterLogin(
      title: 'TFS',
      // logo: 'assets/images/tfs.png',
      messages: LoginMessages(
          usernameHint: '用户名',
          passwordHint: 'TOKEN',
          loginButton: '登录',
          forgotPasswordButton: '如何获取Token?',
          signupButton: '返回'),
      onLogin: _onLogin,
      onSubmitAnimationCompleted: () {
        print('onSubmitAnimationCompleted');
        Navigator.pop(context);
      },
      onRecoverPassword: _onSignUp,
      emailValidator: (s) => null,
      passwordValidator: (s) => s != null && s.isNotEmpty ? null : '',
    );
  }
}
